package com.zelma.house.config;

import com.alibaba.fastjson.JSONObject;
import com.zelma.house.dao.ResourceDao;
import com.zelma.house.entity.ResourceEntity;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

//@Component
public class RunableTesk implements ApplicationRunner {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ResourceDao resourceDao;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("项目初始化把商品信息初始化到ES索引当中");
        List<ResourceEntity> list = resourceDao.selectList(null);
        BulkRequest bulkRequest = new BulkRequest();
        for (ResourceEntity resourceEntity : list) {
            IndexRequest request = new IndexRequest("resource");
            request.id(resourceEntity.getResourceId().toString());
            String jsonString = JSONObject.toJSONString(resourceEntity);
            request.source(jsonString, XContentType.JSON);
            bulkRequest.add(request);
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }
}
